import Vue from 'vue'
import store from '../store'
import Router from 'vue-router'
const originalPush = Router.prototype.push
Router.prototype.push = function push(location) {
   return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)


export const ArryRouter = [
  ...require('./base').default, //基础模块
  ...require('./sys-setting').default, //系统设置
  ...require('./business').default, //业务管理
]

const router = new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: ArryRouter,
})
router.onError((error) => {
  // console.log('routerError', error)
  const pattern = /Loading chunk (\d)+ failed/g;
  const isChunkLoadFailed = error.message.match(pattern);
  const targetPath = router.history.pending.fullPath;
  if (isChunkLoadFailed) {
    router.replace(targetPath);
  }
});

router.beforeEach(async (to, from, next) => {
  const isLogin = !!localStorage.user_token
  
  if (to.path === '/login' || to.path === '/forget'|| to.path === '/mobile') {//登录页，忘记密码，查询手机号
    if (isLogin)
      next('/')
    else
      next()
  } else {
    console.log('isLogin',localStorage.user_token)
    console.log('store.getters.layoutData',store.getters.layoutData)
    if (store.getters.layoutData.length === 0 && isLogin) {
      try {
         store.dispatch({
          type: "base/getLayoutData",
        })
      } catch (err){
        localStorage.removeItem('token')
        next('/login')
        throw err
      }
    }
    
    isLogin ? next() : next('/login')
    next()    // 暂时先放行所有请求
  }
})

export default router;